package com.rms.controller;

import com.alibaba.fastjson.JSONObject;
import com.rms.entity.Dish;
import com.rms.service.DishService;
import com.rms.utils.UserLoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author 胡满意
 * @date 2019/11/7
 */
@RestController
public class DishController {
    @Autowired
    private DishService dishService;

    @GetMapping("/dish")
    @UserLoginToken
    public JSONObject selectAll(){
        JSONObject object = new JSONObject();
        try {
            List<Dish> dishList = dishService.selectAll();
            object.put("dishList",dishList);
            object.put("state","success");
            object.put("message","菜品获取成功");
            return object;
        }catch (Exception e){
            e.printStackTrace();
            object.put("state","error");
            object.put("message","菜品获取失败");
            return object;
        }
    }

    @PostMapping("/dish")
    @UserLoginToken
    public JSONObject insertDish(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        JSONObject object = new JSONObject();
        try {
            String fileName = file.getOriginalFilename();
            String path = "E:/Workspaces/RMS/src/main/webapp/static/images/dish/"+fileName;
            File newFile = new File(path);
            file.transferTo(newFile);
            object.put("state","success");
            object.put("message","菜品增加成功");
            return object;
        }catch (Exception e){
            object.put("state","error");
            object.put("message","菜品增加失败");
            return object;
        }
    }
}
